<%--
   * 【描 述】：岗位管理页面
   * 【环 境】：JAVA 1.7.0_13
   *  @author         柴志鹏  CHAIZP@GMAIL.COM
   *  @version        v1.0 2014-07-17
   *  @since          2014-07-17
 --%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ include file="/include/head.jsp"%>
<html>
  <head>
    <title>岗位管理</title>
    <link rel="stylesheet" type="text/css" href="<%=cssPath%>/MultiSelect.css"/>
    <script type="text/javascript" src="<%=jsPath%>/expand/MultiSelect.js"></script>
    <script type="text/javascript" src="<%=jsPath%>/expand/ItemSelector.js"></script>
    <script type="text/javascript">
    	Ext.onReady(function(){
    		Ext.QuickTips.init();
	    	Ext.form.Field.prototype.msgTarget = 'qtip';
	    	
	    	var subordinateGrid, personGrid;
	    	var dictStore = cf_queryDictByCode('999');
	    	
	    	var jobStore = new Ext.data.Store({//岗位数据源
				proxy: new Ext.data.HttpProxy({
					url: 'JobAction!queryJobList.do'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'total',
					root: 'list'
				}, new Ext.data.Record.create([
					{name: 'cudType'},
					{name: 'id'},
					{name: 'jobName'},
					{name: 'department'},
					{name: 'enableStatus'},
					{name: 'remark'},
					{name: 'createDate', type: 'date'}
				])),
				remoteSort: false,//是否远程排序
				autoLoad: {
					params:{
						start: PAGING_START_INDEX,
						limit: PAGING_PAGE_SIZE
					}
				}
			});
	    	
	    	var jobModel = new Ext.grid.CheckboxSelectionModel({
	    		singleSelect: true,//单选
	    		header: '',//空来代替checkbox全选框
		    	listeners: {
	    			rowselect: function(selModel, rowIndex, record) {//行选中
	    				subordinateStore.baseParams = {
							jobId: record.get('id')
						};
	    				personStore.baseParams = {
							jobId: record.get('id')
						};
						subordinateStore.reload();
						personStore.reload();
	    			}
		    	}
	    	});
	    	var jobCol = new Ext.grid.ColumnModel({
	    		id: 'column',
	    		defaults: {
	    			sortable: true,//默认全部列可排序
	    			align: 'center'
	    		},
	    		columns: [
	    			jobModel,
	    			new Ext.grid.RowNumberer({
	    				id: 'rownum',
	    				header: '序号',
	    				width: 40
	    			}),{
	    				id: 'id',
	    				header: '主键Id',
	    				dataIndex: 'id',
	    				width: 50,
	    				hidden: true
	    			},{
	    				id: 'jobName',
	    				header: '岗位名称',
	    				dataIndex: 'jobName',
	    				width: 50
	    			},{
	    				id: 'department',
	    				header: '所处部门',
	    				dataIndex: 'department',
	    				width: 50,
	    				renderer: function(value, cellmeta, record) {
							var rec = dictStore.find('dictValue',value);
							if(rec!=null && typeof(rec)!=undefined && rec!=-1 && dictStore.getAt(rec).data!=null) {
								return dictStore.getAt(rec).get('dictLabel');
							} else {
								return value;
							}
	    				}
	    			},{
	    				id: 'createDate',
	    				header: '创建时间',
	    				dataIndex: 'createDate',
	    				renderer: Ext.util.Format.dateRenderer(SHORT_DATE_FORMAT),
	    				width: 60
	    			},{
			        	id: 'enableStatus',
			        	header: '启用状态',
			        	dataIndex: 'enableStatus',
			        	width: 60,
			        	renderer: function(value, cellmeta, record) {
			        		if(value){
								return ['<span style="color:red;font-weight:bold;">禁用</span>',
				        				'<span style="color:green;font-weight:bold;">启用</span>']
				        				[value];
							}
			        	}
			        }
	    		]
	    	});
	    	
	    	
	    	var subordinateStore = new Ext.data.Store({//下属数据源
				proxy: new Ext.data.HttpProxy({
					url: 'JobAction!querySubordinateByJobId.do'
				}),
				reader: new Ext.data.JsonReader({
				}, new Ext.data.Record.create([
					{name: 'id'},
		        	{name: 'jobName'},
				    {name: 'enableStatus'}
				])),
				//sortInfo: {field: 'id', direction: 'ASC'},
				remoteSort: false,//是否远程排序
				autoLoad: false
			});
	    	
	    	var subordinateModel = new Ext.grid.CheckboxSelectionModel();
	    	var subordinateCol = new Ext.grid.ColumnModel({
	    		defaults: {
		            sortable: true,// 默认全部列可排序          
		            align: 'center'
		        },
		        columns: [
		        	subordinateModel,
		        	new Ext.grid.RowNumberer({
		        		id: 'rownum',
		        		header: '序号',
						width: 50
					}),{
		        		id: 'roleId',
						header: '主键ID',
						dataIndex: 'id',
						width: 25,
						hidden: true
					},{
		        		id: 'jobName',
			        	header: '岗位名称',
			        	dataIndex: 'jobName',
			      		width: 80
			        },{
			        	id: 'enableStatus',
			        	header: '状态',
			        	dataIndex: 'enableStatus',
			        	width: 50,
			        	renderer: function(value, cellmeta, record) {
			        		return ['<span style="color:red;font-weight:bold;">禁用</span>',
			        				'<span style="color:green;font-weight:bold;">启用</span>']
			        				[value];
			        	}
			        }
		        ]
		    });
	    	
	    	var personStore = new Ext.data.Store({//下属数据源
				proxy: new Ext.data.HttpProxy({
					url: 'JobAction!queryPersonByJobId.do'
				}),
				reader: new Ext.data.JsonReader({
				}, new Ext.data.Record.create([
					{name: 'id'},
					{name: 'username'},
		        	{name: 'personName'},
				    {name: 'mobile'}
				])),
				//sortInfo: {field: 'id', direction: 'ASC'},
				remoteSort: false,//是否远程排序
				autoLoad: false
			});
	    	
	    	var personModel = new Ext.grid.CheckboxSelectionModel();
	    	var personCol = new Ext.grid.ColumnModel({
	    		defaults: {
		            sortable: true,// 默认全部列可排序          
		            align: 'center'
		        },
		        columns: [
		        	personModel,
		        	new Ext.grid.RowNumberer({
		        		id: 'rownum',
		        		header: '序号',
						width: 50	
					}),{
		        		id: 'personId',
						header: '主键ID',
						dataIndex: 'id',
						width: 20,
						hidden: true
					},{
		        		id: 'username',
			        	header: '用户',
			        	dataIndex: 'username',
			      		width: 30
			        },{
		        		id: 'personName',
			        	header: '姓名',
			        	dataIndex: 'personName',
			      		width: 30
			        },{
			        	id: 'mobile',
			        	header: '电话',
			        	dataIndex: 'mobile',
			        	width: 30
			        }
		        ]
		    });
	    	
	    	
	    	//////////////////////////////////////////////////
	    	var viewport = new Ext.Viewport({
	    		layout: 'border',
	    		items: [
	    			new Ext.grid.GridPanel({
	    				id: 'jobGrid',
	    				region: 'west',
	    				autoScroll: true,
					    store: jobStore,
					    cm: jobCol,
					    sm: jobModel,
					    frame: false,
					    trackMouseOver: true,//鼠标经过痕迹
					    loadMask: true,
			        	loadMask: {msg: 'loading...'},
			        	viewConfig: {
			        		forceFit: true,//根据column进行百分比设置
			        		scrollOffset: 0//不加这个的话，会在grid的最右边有个空白，留作滚动条的位置。若不加默认为scrollOffset: 20
			        	},
			        	tbar: [
			        		{
			        			text: '添加',
			        			iconCls: 'addBtn',
			        			handler: function() {
			        				jobController('C', this.text);
			        			}
			        		},{
			        			text: '修改',
			        			iconCls: 'editBtn',
			        			handler: function() {
			        				var record = Ext.getCmp('jobGrid').getSelectionModel().getSelected();
			        				jobController('U', this.text, record);
			        			}
			        		},{
			        			text: '删除',
			        			iconCls: 'deleteBtn',
			        			handler: function() {
			        				var grid = Ext.getCmp('jobGrid');
						    		var record = grid.getSelectionModel().getSelected();
			        				if(record) {
										Ext.MessageBox.confirm('提示', '确认删除?',
											function(btn) {
												if(btn == BUTTON_YES) {
													Ext.Ajax.request({
														url: 'JobAction!jobController.do',
														method: 'POST',
														params: {
															'job.cudType': 'D',
														    'job.id': record.get('id')
														    //'person.optUserId': userId,
														    //'person.optUserName': userName
														},
														success: function(result, request){
															jobStore.remove(record);
															refresh('job');
														},
														failure: function(result, request){
														    Ext.Msg.alert('提示','操作失败!请重试.');
														}
													});
												}
											}
									    )
					            	} else {
					            		Ext.MessageBox.alert('提示', '请选择一条记录.');
					            	}
			        			}
			        		}
			        	],
			        	bbar: cf_getPagingToolbar(PAGING_PAGE_SIZE, jobStore),
			        	listeners: {
			        		rowdblclick: function(grid, rowIndex, event) {//双击事件
			        			//var record = grid.getStore().getAt(rowIndex);
     							//jobController('U', '修改', record);
     							//alert('双击事件');
			        		},
			        		afterrender: function(grid) {//渲染后
		        				setTimeout(function(){
		        					if(grid.getStore().getCount() > 0) {//默认选中首行
				        				grid.getSelectionModel().selectRow(0);
				        			}
		        				}, 500);
			        		}
			        	}
	    			}),
	    			new Ext.TabPanel({
	    				id:'tabs',
				 	    region: 'center',
					    deferredRender: false,
					    activeTab: 0,
					    bodyBorder: false,
					    //bodyStyle: css == 'xtheme-gray.css' ? 'background:#F1F1F1' : 'background:#DFE8F6',
					    enableTabScroll: true,  
					    frame: true,
					    defaults: {
	    					autoScroll: false
	    				},
	    				items: [
	    					{
	    						id: 'subordinateTab',
								title: '下属管理',
								html: '<div id="subordinate" style="height:100%"></div>'
	    					},{
	    						id: 'personTab',
								title: '岗位人员',
								html: '<div id="person" style="height:100%"></div>'
	    					}
	    				],
	    				listeners: {
	    					tabchange: function(tabPanel, panel) {
	    						if(panel.getItemId() == 'subordinateTab') {
	    							if(subordinateGrid) {
	    								subordinateGrid.render();
	    							}
	    						} else if(panel.getItemId() == 'personTab') {
	    							if(personGrid) {
	    								personGrid.render();
	    							}
	    						}
	    						
	    					}
	    				}
	    			})
	    		],
	    		listeners: {
	    			resize: function(viewport, adjWidth, adjHeight, rawWidth, rawHeight) {
	    				var west = Ext.getCmp('jobGrid');
	    				if(Ext.isIE) {
	    					west.setWidth((adjWidth=='auto'?700:adjWidth)*0.5);
	    				} else {
	    					west.setWidth('50%');
	    				}
					}
	    		}
	    	});
	    	
	    	subordinateGrid = new Ext.grid.GridPanel({
	        	id: 'subordinateGrid',
	        	el: 'subordinate',
		        autoScroll: true,
		        autoHeight: true,
		        autoWidth: true,
			    store: subordinateStore,
			    cm: subordinateCol,
			    sm: subordinateModel,
			    border: false,
			    frame: false,
			    trackMouseOver: true,//鼠标经过痕迹
			    loadMask: true,
	        	loadMask: {msg: 'loading...'},
			    viewConfig: {
	        		forceFit: true,//根据column进行百分比设置
	        		scrollOffset: 0
	        	},
	        	tbar: [
	        		{
	        			text: '下属分配',
	        			iconCls: 'addBtn',
	        			handler: function(){
	        				var record = Ext.getCmp('jobGrid').getSelectionModel().getSelected();
	        				if(record) {
	        					setSubordinate(this.text, record.get('id'));
	        				} else {
	        					Ext.MessageBox.alert('提示', '请先选择要分配的岗位.');
	        				}
	        			}
	        		},{
	        			text: '取消分配',
	        			iconCls: 'deleteBtn',
	        			handler: function() {
	        				var records = subordinateGrid.getSelectionModel().getSelections();
					        if (records.length > 0) {
						        Ext.MessageBox.confirm('提示', '确定取消选定岗位?',
									function(btn) {
									    if(btn == BUTTON_YES) {
									    	cf_ShowMessageBox('删除中..');
									        var data = "[";
									        for (var i = 0, len = records.length; i < len; i++){
									        	subordinateGrid.getStore().remove(records[i])
									            data = data + "{id:'"+ records[i].get('id') +"'}";
									            if (i < len - 1) {	data = data + ",";}
									        }
											data = data + "]";
											
											Ext.Ajax.request({
												url: 'JobAction!deleteRelationJob.do',
												method: 'POST',
												params: {jsonData: data},
												success: function (result, request) {
													Ext.MessageBox.alert('操作成功', '共：'+ result.responseText +'条岗位被取消.',
														function(btn) {
															refresh('subordinate');
														}
													);
												},
												failure: function (result, request) {
													Ext.MessageBox.alert('提示', '操作失败!');
									            }
											});
							         	}
									}
						        );
					        } else {
					            Ext.MessageBox.alert('提示', '请选择要取消授权的岗位.');
					            return false;			        
					        }
	        			}
	        		}
	        	]
			});
	    	subordinateGrid.render();
	    	
	    	personGrid = new Ext.grid.GridPanel({
	        	id: 'personGrid',
	        	el: 'person',
		        autoScroll: true,
		        autoHeight: true,
		        autoWidth: true,
			    store: personStore,
			    cm: personCol,
			    sm: personModel,
			    border: false,
			    frame: false,
			    trackMouseOver: true,//鼠标经过痕迹
			    loadMask: true,
	        	loadMask: {msg: 'loading...'},
			    viewConfig: {
	        		forceFit: true,//根据column进行百分比设置
	        		scrollOffset: 0
	        	},
	        	tbar: [
	        		{
	        			text: '人员分配',
	        			iconCls: 'addBtn',
	        			handler: function() {
	        				var record = Ext.getCmp('jobGrid').getSelectionModel().getSelected();
	        				if(record) {
	        					personAuthorization(this.text, record.get('id'));
	        				} else {
	        					Ext.MessageBox.alert('提示', '请选择相应岗位.');
	        				}
	        			}
	        		},	        		{
	        			text: '删除人员',
	        			iconCls: 'deleteBtn',
	        			handler: function() {
	        				var records = personGrid.getSelectionModel().getSelections();
					        if (records.length > 0) {
						        Ext.MessageBox.confirm('提示', '确定删除选定人员?',
									function(btn) {
									    if(btn == BUTTON_YES) {
									    	cf_ShowMessageBox('删除中..');
									    	var job = Ext.getCmp('jobGrid').getSelectionModel().getSelected();
									        var data = "[";
									        for (var i = 0, len = records.length; i < len; i++){
									        	personGrid.getStore().remove(records[i])
									            data = data + "{jobId:'"+ job.get('id') +
									            	"', personId:'" + records[i].get('id') +"'}";
									            if (i < len - 1) {	data = data + ",";}
									        }
											data = data + "]";
											
											Ext.Ajax.request({
												url: 'JobAction!deleteRelationPerson.do',
												method: 'POST',
												params: {jsonData: data},
												success: function (result, request) {
													Ext.MessageBox.alert('操作成功', '共删除关联人员：'+ result.responseText +'人.',
														function(btn) {
															refresh('person');
														}
													);
												},
												failure: function (result, request) {
													Ext.MessageBox.alert('提示', '操作失败!');
									            }
											});
							         	}
									}
						        );
					        } else {
					            Ext.MessageBox.alert('提示', '请选择要取消授权的岗位.');
					            return false;			        
					        }
	        			}
	        		}
	        	]
			});
	    	
	    	function setSubordinate(title, jobId) {
	    		// 临时岗位操作容器
	    		var arrResult = new Array();
			    var optGrid = new Ext.grid.GridPanel({
					id: 'optGrid',
					title: '<div style="text-align:center;">可选岗位</div>',
					autoScroll: true,
					border: false,
					store: new Ext.data.JsonStore({  
					    url: 'JobAction!getOptionalJob.do',
					    fields: [
						    {name: 'id'},
							{name: 'jobName'},
						    {name: 'department'}
					    ],
					    autoLoad: {
					    	params: {
					    		'jobId': jobId
					    	}
					    }
					}),
					cm: new Ext.grid.ColumnModel({
						defaults: {
							sortable: false,//禁止排序
							align: 'center'
						},
						columns: [
							{id: 'id', 			header: '主键Id', 	dataIndex: 'id', 		width: 10, hidden: true},
							{id: 'jobName', 	header: '岗位名称', 	dataIndex: 'jobName', 	width: 40},
							{id: 'department', 	header: '所在部门', 	dataIndex: 'department',width: 40, 
								renderer: function(value, cellmeta, record) {
									var rec = dictStore.find('dictValue',value);
									if(rec!=null && typeof(rec)!=undefined && rec!=-1 && dictStore.getAt(rec).data!=null) {
										return dictStore.getAt(rec).get('dictLabel');
									} else {
										return value;
									}
			    				}
							}
						]
					}),
					stripeRows: true,
					//trackMouseOver: true,// 鼠标划过痕迹
					loadMask: true,
					loadMarks: {msg: 'loading..'},
					viewConfig: {
						forceFit: true//根据column进行百分比设置
					},
					listeners: {
						//行双击事件
						'rowdblclick': function(grid, rowIndex, event) {
							//获取选中行
							var record = grid.getSelectionModel().getSelected();
                        	grid.store.remove(record);
                        	selGrid.store.insert(selGrid.store.getCount(), record);
                        	arrResult.push({//将选择的岗位添加到临时数据
				        		id: record.get('id'),
				        		isSelected: true//选择岗位
				        	});
						}
					}
				});
				
				var selGrid = new Ext.grid.GridPanel({
					id: 'selGrid',
					title: '<div style="text-align:center;">已选岗位</div>',
					autoScroll: true,
					border: false,
					store: new Ext.data.JsonStore({  
					    url: 'JobAction!getSelectedJob.do',
					    fields: [
						    {name: 'id'},
							{name: 'jobName'},
						    {name: 'department'} 
					    ],
					    autoLoad: {
					    	params: {
					    		'jobId': jobId
					    	}
					    }
					}),
					cm: new Ext.grid.ColumnModel({
						defaults: {
							sortable: false,//禁止排序
							align: 'center'
						},
						columns: [
							{id: 'id', 			header: '主键Id', 	dataIndex: 'id', 		width: 10, hidden: true},
							{id: 'jobName', 	header: '岗位名称', 	dataIndex: 'jobName', 	width: 40},
							{id: 'department', 	header: '所在部门', 	dataIndex: 'department',width: 40, 
								renderer: function(value, cellmeta, record) {
									var rec = dictStore.find('dictValue',value);
									if(rec!=null && typeof(rec)!=undefined && rec!=-1 && dictStore.getAt(rec).data!=null) {
										return dictStore.getAt(rec).get('dictLabel');
									} else {
										return value;
									}
			    				}
							}
						]
					}),
					stripeRows: true,
					//trackMouseOver: true,// 鼠标划过痕迹
					loadMask: true,
					loadMarks: {msg: 'loading..'},
					viewConfig: {
						forceFit: true//根据column进行百分比设置
					},
					listeners: {
						'rowdblclick': function(grid, rowIndex, event) {
							var record = grid.getSelectionModel().getSelected();
							grid.store.remove(record);
							optGrid.store.insert(optGrid.store.getCount(), record);
							arrResult.push({//将移除的岗位添加到临时数据
				        		id: record.get('id'),
				        		isSelected: false//移除岗位
				        	});
						}
					}
				});
				
				
				var win = new Ext.Window({
					title: title,
					layout: 'column',
					width: 500,
					height: 300,
					modal: true,
					closeAction: 'close',
					resizable: false,
					constrainHeader: true,
					buttonAlign: 'center',
					items: [{
						columnWidth: .47,
						items: [optGrid]
					}, {
						columnWidth: .06,
						items: [
							new Ext.Panel({
								id: 'prcBtns',
								border: false,
								defaults: { xtype: 'button' },
								layout: {
									type: 'vbox',
									pack: 'center',//纵向对齐方式 start：从顶部；center：从中部；end：从底部
									align: 'center'//对齐方式 center、left、right：居中、左对齐、右对齐；stretch：延伸；stretchmax：以最大的元素为标准延伸
								},
								items: [
									{
										text: '&gt;&gt;',//>>
										handler: function() {
											//获取选中的"可选"行
											var records = optGrid.getSelectionModel().getSelections();
											if(records.length != 0) {
												//循环选中并移除store，将其插入到"已选"数据源中
												Ext.each(records, function(r) {
						                        	optGrid.store.remove(r);
						                        	selGrid.store.insert(selGrid.store.getCount(), r);
						                        	arrResult.push({//将选择的岗位添加到临时数据
										        		id: r.get('id'),
										        		isSelected: true//选择岗位
										        	});
						                        });
											}
										}
									}, {
										//换行
										xtype: 'panel',
										border: false,
										html: '<br/><br/>'
									},{
										text: '&lt;&lt;',//<<
										handler: function() {
											//获取选中的"已选"行
											var records = selGrid.getSelectionModel().getSelections();
											if(records.length != 0) {
												//循环选中并移除store，将其插入到"可选"数据源中
												Ext.each(records, function(r) {
													selGrid.store.remove(r);
													optGrid.store.insert(optGrid.store.getCount(), r);
													arrResult.push({//将移除的岗位添加到临时数据
										        		id: r.get('id'),
										        		isSelected: false//移除岗位
										        	});
												});
											}
										}
									}
								]
							})
						]
					}, {
						columnWidth: .47,
						items: [selGrid]
					}],
					listeners: {
						'afterrender': function(win) {
							optGrid.setHeight(win.height-66);
							selGrid.setHeight(win.height-66);
							Ext.getCmp('prcBtns').setHeight(win.height-66);
						}
					},
					buttons: [
						{
							text: '保存',
							handler: function() {
								cf_ShowMessageBox('保存中..');
								
								var results = new Array();//定义一个返回结果数组
							    for (var i = 0; i < arrResult.length; i++) {
								    var index = -1;  // 函数返回值用于布尔判断
								    for (var j = 0; j < results.length; j++) {
								        if (results[j].id == arrResult[i].id) {
								            index = j; //如果重复,返回当前index
								            break;
								        }
								    }
							        if (index == -1) {//把不重复的记录放入新数组
							            results.push(arrResult[i]);
							        } else {//重复的记录取最后一个,因为要获得最后的选项
							        	results.removeAt(index);
							        	results.insert(i,arrResult[i]);
							        }
							    }

								var data = "[";
								for(var i = 0, len = results.length; i < len; i++) {
									data += "{jobId:"+ jobId +","
									data += "subordinateId:"+ results[i].id +","
									data += "isSelected:"+ results[i].isSelected +"}"
									if (i < len - 1)	data = data + ",";
								}
								data += "]";

								Ext.Ajax.request({
									url: 'JobAction!relationJobController.do',
									method: 'POST',
									params: {
										'data': data
									},
									success: function(result, request) {
										win.hide('audit', function() {
	            							win.close();
	            							Ext.MessageBox.alert('提示', '操作成功.');
	            							refresh('subordinate');
	            						}, true);
									},
									failure: function(result, request) {
										Ext.MessageBox.alert('提示', '操作失败!请重试.');
									}
								});
							}
						}, {
							text: '取消',
							handler: function() {
								win.hide('jobManager', function() {
           							win.close();
           						}, true);
							}
						}
					]
				});
				win.show('jobManager');
	    	}
	    	
	    	function personAuthorization(title, jobId) {
				var recordsChecked = new Array();// 选中的Record列表 
	    		var store = new Ext.data.Store({//角色数据源
					proxy: new Ext.data.HttpProxy({
						url: 'JobAction!getSelectedPersonList.do'
					}),
					reader: new Ext.data.JsonReader({
						totalProperty: 'total',
						root: 'list'
					}, new Ext.data.Record.create([
						{name: 'id'},
						{name: 'username'},
			        	{name: 'personName'},
					    {name: 'mobile'},
					    {name: 'checked'}
					])),
					remoteSort: false,//是否远程排序
					autoLoad: true,
					baseParams: {
						start: PAGING_START_INDEX,
						limit: 10,
						jobId: jobId
					},
					listeners : {
	                    load: function(store, records, options) {
	                        var arrays = new Array();
	                        store.each(function(record) {
	                            if (record.get('checked') == 'true') {
	                            	arrays.push(record);//将被选中的添加到集合
	                            }
	                        });
	                        selModel.selectRecords(arrays);//将集合内的进行选中
	                    }
					}
				});
				var RecordSet = Ext.data.Record.create([
					{name: 'jobId'},
			    	{name: 'personId'},
		    	   	{name: 'checked'}
			    ]);
				var selModel = new Ext.grid.CheckboxSelectionModel({
					listeners: {
						'rowselect': function(selModel, rowIndex, record) {//行选中
							var rs = new RecordSet({
				        		jobId: jobId,
				        		personId: record.get('id'),
				        		checked: selModel.isSelected(rowIndex)
				        	});
				        	recordsChecked.push(rs);
						},
						'rowdeselect': function(selModel, rowIndex, record) {//取消选中
							var rs = new RecordSet({
				        		jobId: jobId,
				        		personId: record.get('id'),
				        		checked: selModel.isSelected(rowIndex)
				        	});
				        	recordsChecked.push(rs);
						}
					}
				});
				var colModel = new Ext.grid.ColumnModel({
		    		defaults: {
			            sortable: true, // 默认全部列可排序          
			            align: 'center'
			        },
			        columns: [
			        	selModel,
			        	new Ext.grid.RowNumberer({
			        		id: 'rownum',
			        		header: '序号',
							width: 50
						}),{
			        		id: 'roleId',
							header: '主键ID',
							dataIndex: 'id',
							width: 25,
							hidden: true
						},{
			        		id: 'username',
				        	header: '用户',
				        	dataIndex: 'username',
				      		width: 50
				        },{
				        	id: 'personName',
				        	header: '姓名',
				        	dataIndex: 'personName',
				        	width: 50
				        },{
				        	id: 'mobile',
				        	header: '移动电话',
				        	dataIndex: 'mobile',
				        	width: 50
				        }
			        ]
			    });
		        var jobAuth = new Ext.grid.GridPanel({
		        	id: 'jobAuth',
			        autoScroll: true,
				    store: store,
				    cm: colModel,
				    sm: selModel,
				    frame: false,
				    trackMouseOver: true,//鼠标经过痕迹
				    loadMask: true,
		        	loadMask: {msg: 'loading...'},
				    tbar: ['->','姓名',
			        	new Ext.form.TwinTriggerField({
						    trigger1Class: 'x-form-clear-trigger',
						    trigger2Class: 'x-form-search-trigger',
						    hideTrigger1: true,
						    autoWidth: true,
						    listeners: {
						        'specialkey': function(f, e){
						        	if(e.getKey() == e.ENTER){
						            	this.onTrigger2Click();
						        	}
						    	}
						 	},
						 	onTrigger1Click:function(){
						    	this.setRawValue('');
						     	this.triggers[0].hide();
						    	return false;
						 	},
						 	onTrigger2Click:function(){
						    	var name = this.getRawValue().replace(/(^\s*)|(\s*$)/g, "");//去前后空格
					        	this.triggers[0].show();
						        store.reload({
						        	params: {
						        		start: PAGING_START_INDEX,
										limit: 10,
						        		personName: name
						        	}
						    	});
							}
						})],
				    bbar: cf_getPagingToolbar(10, store),
				    viewConfig: {
		        		forceFit: true,//根据column进行百分比设置
		        		scrollOffset: 0//不加这个的话，会在grid的最右边有个空白，留作滚动条的位置。若不加默认为scrollOffset: 20
		        	}
		        });
	    		var win = new Ext.Window({
		            title: title,
		            layout: 'fit',
		            width: 350,
		            height: 360,
		            modal: true,
		            closeAction: 'close',
		            resizable: false,
		            items: jobAuth,
		            constrain: false,//禁止窗口移出浏览器
					constrainHeader: true,//禁止窗口移出浏览器
					buttonAlign: 'right',
					buttons: [{
						text: '确定',
						handler: function() {
							var records = filterDupFunctionRecord(recordsChecked, 'personId');
            				if (recordsChecked.length < 1 || records.length < 1) {
					       		Ext.MessageBox.alert('提示', '数据没有任何改变!');
					       		return false;
					       	}
            				cf_ShowMessageBox('保存中..');
					       	var data = "[";
					       	for(var i = 0,len = records.length; i < len; i++) {
					       		data = data + "{jobId:'" + records[i].get('jobId') +
					       				"', personId:'" + records[i].get('personId') +
					       				"', checked:'" + records[i].get('checked') +
					            		"'}";
					            if (i < len - 1) {data = data + ",";}
					       	}
					       	data = data + "]";
					       	
					       	Ext.Ajax.request({
								url: 'JobAction!relationPersonController.do',
								method: 'POST',
								params: {jsonData: data},
								success: function (){
									Ext.MessageBox.alert('提示', '操作成功',
									function(btn) {
										win.hide('jobManager', function(){
											refresh('person');
											win.close();
										} ,true);
									});
								},
								failure: function (){
									Ext.MessageBox.alert('提示', '操作失败');
					            }
							});	
            			}
					},{
						text: '取消',
						handler: function() {
							win.hide('jobManager', function() {	// 淡入窗口
		                    	win.close();						// 关闭
		                    }, true);
						}
					}]
		        });
		        win.show('jobManager');// 淡出窗口
	    	}
	    	
	    	function jobController(cudType, title, record) {
	    		var jobForm = new Ext.form.FormPanel({
	    			id: 'jobForm',
	    			region: 'center',
		            autoScroll: true,
		            layout: 'form',
		            labelWidth: 70,
		            labelAlign: 'right',
		            bodyStyle: 'padding:5px 5px 0',
		            border: true,
		            frame: true,
		            fileUpload: true,
		            buttonAlign: 'center',
		            defaults: {
						anchor: '90%'
		            },
		            items:[
		            	new Ext.form.Hidden({
		            		id: 'id',
			            	name: 'job.id'
			            }),
						new Ext.form.TextField({
							id: 'jobName',
							fieldLabel: cf_getRequiredItem('岗位名称'),
							name: 'job.jobName',
							maxLength: 50,
							maxLengthText: '名称长度不可大于{0}字符',
							allowBlank: false
						}),
						new Ext.form.ComboBox({// 下拉菜单
		            		id: 'department',
							fieldLabel: cf_getRequiredItem('所属部门'),
							xtype: 'combo',
							hiddenName: 'job.department',
							store: dictStore,
							valueField: 'dictValue',
							displayField: 'dictLabel',
							loadingText: 'loading...',
							mode: 'local',
							triggerAction: 'all',
							editable: false,
							allowBlank: false
						}),
						new Ext.form.RadioGroup({// 单选按钮
							id: 'enableStatus',
							fieldLabel: '使用状态',
							columns: [50,50],// 列间距
		           			items: [
		           				{boxLabel: '启用', inputValue: 1, name: 'job.enableStatus', checked: true},
		           				{boxLabel: '禁止', inputValue: 0, name: 'job.enableStatus'}
		           			]
						}),
						new Ext.form.TextArea({
							id: 'remark',
							fieldLabel: '备注',
							name: 'job.remark'
						})
		            ]
	    		});
	    		
	    		win = new Ext.Window({
		            title: title,
		            layout: 'border',
		            width: 350,
		            height: 235,
		            modal: true,
		            closeAction: 'close',
		            resizable: false,
		            items: jobForm,
		            constrain: false,//禁止窗口移出浏览器
					constrainHeader: true,//禁止窗口移出浏览器
					buttonAlign: 'center',
					buttons: [{
		                text: '保存',
		                handler: function() {
		            		if(!(jobForm.form.isValid())) {
		                    	return false;
		                    } else {
		                    	jobForm.getForm().submit({
									url: 'JobAction!jobController.do',
									method: 'POST',
									submitEmptyText: false,
									params: {
										'job.cudType': cudType
									},
									success: function (result, request) {
										win.hide('jobManager', function() {	// 淡入窗口
											refresh('job');	// 刷新
						                	win.close();						// 关闭
						                }, true);
									},
									failure: function (result, request) {
										Ext.MessageBox.alert('提示', '操作失败!');
						            }
								});
		                    }
		                }
		            },{
		                text: '取消',
		                handler: function() {
		                    win.hide('jobManager', function() {	// 淡入窗口
		                    	win.close();						// 关闭
		                    }, true);
		                }
		            }],
					listeners: {
		        		beforerender: function(win) {//渲染前
	    					if(cudType == 'U') {//修改
				    			jobForm.getForm().loadRecord(record);
				    		}
		        		}
		            }
		        });
		        win.show('jobManager');// 淡出窗口
	    	}
	    	
	    	
	    	function refresh(type) {
		    	if(type == 'job') {
		    		jobStore.modified = [];
		           	jobStore.removeAll();
		  			jobStore.reload();
		    	} else if(type == 'subordinate') {
		    		subordinateStore.modified = [];
		           	subordinateStore.removeAll();
		  			subordinateStore.reload();
		    	} else if(type == 'person') {
		    		personStore.modified = [];
		           	personStore.removeAll();
		  			personStore.reload()
		    	}
		    }
	    	
	    	function filterDupFunctionRecord(receiveArray, filterId) {//过滤数组中的重复记录
			    var arrResult = new Array();//定义一个返回结果数组
			    for (var i = 0; i < receiveArray.length; i++) {
			    	var index = isDuplicateFunction(arrResult, receiveArray[i], filterId);
			        if (index == -1) {//把不重复的记录放入新数组
			            arrResult.push(receiveArray[i]);
			        } else {//重复的记录取最后一个,因为要获得最后的选项
			        	arrResult.removeAt(index);
			        	arrResult.insert(i,receiveArray[i]);
			        }
			    }
			    return arrResult;
			}
	    	
	    	function isDuplicateFunction(receiveArray, checkItem, filterId) { //判断记录是否重复
			    var index = -1;  // 函数返回值用于布尔判断
			    for (var i = 0; i < receiveArray.length; i++) {
			        if (receiveArray[i].get(filterId) == checkItem.get(filterId)) {
			            index = i; //如果重复,返回当前index
			            break;
			        }
			    }
			    return index;
			}
	    });
    	
    </script>
  </head>
  
  <body>
    <div id="jobManager"></div>
  </body>
</html>
